
<!-- 发布组件 -->
<template>
    <div id="container">
        <el-form 
            label-position="top" 
            label-width="100px" 
            :model="ruleForm" 
            :rules="rules" 
            style="max-width: 460px"
            class="demo-ruleForm"
            ref="ruleFormRef">
            <el-form-item label="竞品名称" prop="name">
                <el-input v-model="ruleForm.name" />
            </el-form-item>
            <el-form-item label="底价" prop="price">
                <el-input v-model.number="ruleForm.price" />
            </el-form-item>
            <el-form-item label="加价幅度" prop="incrementPrice">
                <el-input v-model.number="ruleForm.incrementPrice" />   
            </el-form-item>
            <el-form-item label="开拍时间" prop="date">
                <el-date-picker v-model="ruleForm.auctionTime" type="datetime" placeholder="选择开拍时间" />
            </el-form-item>
            <el-form-item label="图片">
                <UpLoad ref="uploadBtn" />
            </el-form-item>
        </el-form>
        <button id="publishBtn" @click="submitForm(ruleFormRef)">发布</button>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, inject } from 'vue';
import UpLoad from '../components/UpLoad.vue';
import { FormInstance, FormRules, ElMessage } from 'element-plus'
import moment from 'moment';
import axios from 'axios';
import { useUserStore } from '../stores/user';

const userStore = useUserStore();

// 请求根路径
const BASEURL = inject("apiBaseUrl");

// 获取上传组件元素
let uploadBtn = ref(null);

// 发布触发
const submitForm = async (formEl: FormInstance | undefined) => {
    // 验证选择的时间合法性（需要大于当前时间）
    const dateFlag: boolean = moment(ruleForm.auctionTime).valueOf() > moment(new Date()).valueOf();
    // 是否选择了图片
    const pictureFlag: boolean = uploadBtn.value.isSelected;

    if(!dateFlag){
        ElMessage("选择的时间要大于当前时间哦~")
        return;
    }

    if(!pictureFlag){
        ElMessage("需要选择图片哦~")
        return;
    }

    // 表单验证
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid && dateFlag) {
            // 表单提交逻辑
            if (uploadBtn.value) {
                // 上传图片和数据,调用数据上传方法
                subData()
            }
        } else {
            console.log('表单验证异常!', fields)
        }
    })
}

// 上传数据
function subData(){
    // 提交图片，获取返回的随机图片名称
    uploadBtn.value.submitUpload()
    setTimeout(async ()=>{
        // 获取返回的图片
        let returnPictureName = uploadBtn.value.returnPicName;
        if(returnPictureName == "no"){
            ElMessage("图片上传失败，请重试");
            return;
        }
        // 构造字段：图片名称， 发布者名称，拥有者名称
        ruleForm.pictureName = returnPictureName
        ruleForm.publisher = userStore.userInfo.name;
        ruleForm.ownerName = userStore.userInfo.name;
        const res = await axios.post(`${BASEURL}/auctionProducts`, ruleForm);
        if(res.data.code != 1){
            // 提示发布失败
            ElMessage({
                type:"warning",
                message: "添加失败，请稍后重试!"
            })
        }
        // 修改用户的竞品发布数量
        await axios.put(`${BASEURL}/users/updatePubNumber/${userStore.userInfo.uid}`)
        // 添加成功，置空表单，提示成功
        Object.keys(ruleForm).forEach((key)=>(ruleForm[key]=""));
        // 清除所有文件
        uploadBtn.value.clearSelectFiles();
        ElMessage({
                type:"success",
                message: "发布成功!"
            })
    }, 500)
}

interface PublishData {
    name: string,
    price: number | null,
    incrementPrice: number | null,
    auctionTime: Date | null,
    pictureName: string,
    publisher: string,
    ownerName:string
}

// 表单校验
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<PublishData>({
    name: '',
    price: null,
    incrementPrice: null,
    auctionTime: null,
    pictureName: "",
    publisher:"",
    ownerName: ""
})

const rules = reactive<FormRules<PublishData>>({
    name: [
        { required: true, message: '必填项', trigger: 'blur' },
    ],
    price: [
        { required: true, message: '必填项', trigger: 'blur'},
        { type: 'number', message: '请填入数值' }
    ],
    incrementPrice: [
        { required: true, message: '必填项', trigger: 'blur' },
        { type: 'number', message: '请填入数值' }
    ],
    auctionTime: [
        { required: true, message: '必填项', trigger: 'blur' },
    ],
    pictureName: [
        { required: true, message: '必填项', trigger: 'blur' },
    ]
})

</script>


<style scoped>
* {
    padding: 0px;
    margin: 0px;
    box-sizing: border-box;
}

#container {
    padding: 25px;
    height: 100%;
    background-color: #f6f0e7;
}

#publishBtn {
    width: 130px;
    height: 50px;
    background-color: #b24c5b;
    border-radius: 7px;
    border: none;
    color: white;
    cursor: pointer;
    margin-top: 10px;
    margin-left: 150px;
}

#publishBtn:hover {
    background-color: #b24c5bd2;
}


.el-form-item{
    margin-top: 15px;
}
</style>